import { createRouter, createWebHashHistory } from 'vue-router';
import type { RouteRecordRaw, Router } from 'vue-router';
import type { App } from "vue";

import Layout from '@/views/layout/index.vue'

// 静态路由
export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue'),
    meta: { hidden: true }
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'Home' }
      }
    ]
  },
]

// 404 路由，在动态路由之后加入路由表
export const notFoundRoute: RouteRecordRaw = {
  path: '/:pathMatch(.*)*',
  name: 'NotFound',
  component: () => import('../views/errorMessagePage/index.vue'),
  meta: { hidden: true }
}

// Mock 菜单数据
export const mockMenuData = [
  {
    "path": "/system",
    "name": "System",
    "component": "Layout",
    "meta": {
      "title": "系统管理",
      "icon": "Setting"
    },
    "children": [
      {
        "path": "order",
        "name": "Order",
        "component": "system/order/index.vue",
        "meta": {
          "title": "订单管理",
          "icon": "Order"
        }
      },
      {
        "path": "user",
        "name": "User",
        "component": "system/user/index.vue",
        "meta": {
          "title": "用户管理",
          "icon": "User"
        }
      },
      {
        "path": "businessDataChart",
        "name": "BusinessDataChart",
        "component": "system/businessDataChart/index.vue",
        "meta": {
          "title": "运营数据统计",
          "icon": "User"
        }
      }
    ]
  },
  {
    "path": "/content",
    "name": "Content",
    "component": "Layout",
    "meta": {
      "title": "内容管理",
      "icon": "Document"
    },
    "children": [
      {
        "path": "article",
        "name": "Article",
        "component": "content/article/index.vue",
        "meta": {
          "title": "文章管理",
          "icon": "Document"
        }
      },
      {
        "path": "category",
        "name": "Category",
        "component": "content/category/index.vue",
        "meta": {
          "title": "分类管理",
          "icon": "Folder"
        }
      }
    ]
  }
]

// 加载组件
const loadComponent = (component: string) => {
  if (component === 'Layout') {
    return Layout
  }
  // return () => import(`@/views/${component}`)
  return () => import(/* @vite-ignore */ `../views/${component}`)
}

// 处理路由组件
const handleRoutes = (routes: any[]): RouteRecordRaw[] => {
  return routes.map(route => {
    const newRoute: RouteRecordRaw = {
      path: route.path,
      name: route.name,
      component: loadComponent(route.component),
      meta: route.meta
    }

    if (route.children && route.children.length) {
      // @ts-ignore
      newRoute.children = handleRoutes(route.children)
    }
    return newRoute
  })
}

// 动态添加路由
export const addDynamicRoutes = (router: Router) => {
  const asyncRoutes = handleRoutes(mockMenuData)
  asyncRoutes.forEach(route => {
    router.addRoute(route)
  })

  // 确保 404 放到最后（动态路由之后）。解决刷新浏览器，页面404报错
  if (!router.hasRoute('NotFound')) {
    router.addRoute(notFoundRoute)
  }

  return asyncRoutes
}

/**
 * 创建路由表
 */
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes as RouteRecordRaw[],
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 })
});


// 全局注册 router
export function setupRouter(app: App<Element>) {
  app.use(router);
}

export default router;